package com.imti.xmldemo;

import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyHandler extends DefaultHandler
{

    private List<Person> mPersonList;

    private Person mPerson;

    private String mTag;

    public List<Person> getmPersonList()
    {
        return mPersonList;
    }
    //文档解析开始
    @Override
    public void startDocument() throws SAXException
    {
        super.startDocument();

        mPersonList = new ArrayList<>();
    }

    //文档解析结束
    @Override
    public void endDocument() throws SAXException
    {
        super.endDocument();
    }

    //标签开始
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException
    {
        super.startElement(uri, localName, qName, attributes);

        //扫描到开始标签为<person>时，创建List元素，并获取属性
        if (localName.equals("person"))
        {
            mPerson = new Person();

            mPerson.setId(attributes.getValue("id"));
        }
        //通过成员变量mTag，缓存标签，用于在characters()方法中判断当前标签
        mTag = localName;
    }
    //标签结束
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException
    {
        super.endElement(uri, localName, qName);

        if (localName.equals("person"))
        {
            mPersonList.add(mPerson);

            //由于列表中多条数据结构相同，所以解析结束一条Person数据后，需要将Person对象置空
            mPerson = null;
        }

        //因为有多个标签需要缓存标签名，mTag会被重复赋值，所以在一条Person数据解析完成后，
        //mTag需要置空
        mTag = null;
    }

    //获取数据
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        super.characters(ch, start, length);

        //由于标签缓存可能为null，故判非空
        if (!TextUtils.isEmpty(mTag))
        {
            switch (mTag)
            {
                case "name":
                    mPerson.setName(new String(ch, start, length));
                    break;

                case "age":
                    mPerson.setAge(new String(ch, start, length));
                    break;
            }
        }
    }
}
